package guestbook;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.String;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/* this function connects to the url, parses the data and returns a parsed array*/
public class parsingSites {
	
	//this value is here to ensure we got 16 elements from the XML
	
	public static String[] parsingData(String location,String field,int flag,int fieldsNum,int modResult){

		  try
		  {
			  MyUrl url = new MyUrl(location);
			  String xmlAsString=createStringFromHtml(url);	         
			 		  
			  /* the following section summons the db parser class with the given XML file*/
			  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			  DocumentBuilder db = dbf.newDocumentBuilder();
			  InputSource is=new InputSource();
			  is.setCharacterStream(new StringReader(xmlAsString));
			  Document doc= db.parse(is);
			  doc.getDocumentElement().normalize();
			  NodeList nodeLst = doc.getElementsByTagName(field);
			  String[] data=new String[16];
			    
			  /* iterate on the XML field(var) and get the data, builds an array*/
	
			 for (int i=0;i<nodeLst.getLength();i++){
				  Node fstNode = nodeLst.item(i);
				  if (flag==0){
					  data[i]=fstNode.getTextContent();
					  if ((data[i]=="null")||(data[i]==null)) return null; 
				  }
			  }
			 
			 //this if verifies we actually have valid data to put in the DB
			 if (nodeLst.getLength()==0) return null;
					 
			 // if we have actual data, the array is valid and we return it.
			 return data;
		  
		  }
		  catch (Exception e) 
		  {
		    e.printStackTrace();
		    return null;
		  }
	 }
	/* the function below runs a loop to try and parse the xml, untill success*/
	public static String[] getDataFromXml(String[] result,String field,String url ){
		int i=0;
		result=null;
		while ((result==null)&& (i<5)){
			result=parsingData(url,field,0,3,2);
			i++;
		}
		return result;
	}
	
	//this method creates a string that contains the html code of url
	public static String createStringFromHtml(MyUrl url){
		try
		{
			BufferedReader reader = new BufferedReader(new InputStreamReader(url.getUrl().openStream(),"UTF-8"));
            String line;
            String xmlAsString="";

            while ((line = reader.readLine()) != null) {
                xmlAsString+=line;
            }
            reader.close();
			return xmlAsString;
		}
		catch (Exception e)
		{
			return null;
		}	
		
	}
		
}